package com.atguigu.springcloud.service.impl;

import cn.hutool.core.util.IdUtil;
import com.atguigu.springcloud.service.PaymentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

@Service
public class PaymentServiceImpl implements PaymentService {
    @Override
    public String paymentInfo_OK(Integer id) {
        return "线程池： " + Thread.currentThread().getName() + "  paymentInfo_OK, id: " + id + "\t";
    }

    @Override
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeoutHandler", commandProperties = {
            // 设置超时时间3秒钟
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")
    })
    public String paymentInfo_Timeout(Integer id) {
        // int i = 10 / 0;
        int time = 3;
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
        }
        return "线程池： " + Thread.currentThread().getName() + " paymentInfo_Timeout, id: " + id + "\t" + "秏时(秒):" + time;
    }

    public String paymentInfo_TimeoutHandler(Integer id) {
        return "线程池： " + Thread.currentThread().getName() + "paymentInfo_TimeoutHandler, id: " + id + "\t" + "调用超时";
    }

    // == 服务熔断
    // 当在十秒钟内有十次请求中存在百分之六十的请求发生错误将会导致服务熔断，当错误请求慢慢减少后恢复正常
    //以下property的name属性在HystrixCommandProperties类中声明，相关可以查看源码中的注释
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),    // 开启熔断
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),     // 请求次数，十次请求，
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),    // 十秒钟，时间范围
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")    // 错误百分比，失败率达到多少后跳闸
    })
    public String paymentCircuitBreaker(Integer id) {
        if (id < 0) {
            throw new RuntimeException("*****id 不能为负数*****");
        }
        String serialNumber = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "\t" + "调用成功，流水号：" + serialNumber;
    }

    public String paymentCircuitBreaker_fallback(Integer id) {
        return "id 不能为负数，请稍后再试！！   id： " + id;
    }
}
